package com.example.myblog.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyService {
    @Resource
    private JavaMailSender sender;//邮件发送
    private LineCaptcha lineCaptcha;//图像验证码
    @Resource
    private StringRedisTemplate template;//redis缓存

    @Value("${spring.mail.username}")
    private String from;
    @Value("${expiretime}")
    private String expireTime;

    public void getTextCode(String email) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject("[博客系统]您的注册验证码");
        Random random = new Random();
        int code = random.nextInt(899999) + 100000;
        System.out.println(code);
        template.opsForValue().set("text-code:" + email, code + "", Long.parseLong(expireTime), TimeUnit.SECONDS);
        mailMessage.setText("您的注册验证码为：" + code + ",三分钟内有效，请及时完成注册！如果不是本人请忽略。");
        mailMessage.setTo(email);
        mailMessage.setFrom(from);
        sender.send(mailMessage);
    }

    public boolean doTextVerify(String email, String code) {
        String value = template.opsForValue().get("text-code:" + email);
        return value != null && value.equals(code);
    }

    public void getImageCode(HttpServletRequest request, HttpServletResponse response) {
        //HuTool定义图形验证码的长和宽,验证码的位数，干扰线的条数
        lineCaptcha = CaptchaUtil.createLineCaptcha(100, 36, 4, 10);
        System.out.println(lineCaptcha.getCode() + "验证码的值");
        request.getSession().setAttribute("image-code", lineCaptcha.getCode());
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            lineCaptcha.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean doImageVerify(HttpSession session, String code) {
        String value = (String) session.getAttribute("image-code");
        System.out.println(value + " : " + code);
        return value != null && value.equals(code);
    }
}
